<template>
  <div>
    <!-- 权限点数据展示 -->
    <el-tree
      ref="refTree"
      :data="list"
      node-key="id"
      default-expand-all
      :show-checkbox="true"
      :check-strictly="true"
      :props="{ label: 'name' }"
    />
    <div style="text-align: right;">
      <el-button right @click="hCancel">取消</el-button>
      <el-button type="primary" @click="hSubmit">确定</el-button>
    </div>
  </div>
</template>

<script>
import { getPermissionList } from '@/api/permissions'
import { tranListToTreeData } from '@/utils/index'
import { assignPerm, getRoleDetail } from '@/api/settings'
export default {
  props: {
    roleId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      list: [] // 存储权限数据
    }
  },
  created() {
    this.loadPermissionList() // 调用接口，获取所有的权限点数据
    this.loadPermissionByRoleId() // 获取当前这角色已经具备的权限
  },
  methods: {
    async loadPermissionList() {
      try {
        // 发送请求 获取权限列表
        const res = await getPermissionList()
        console.log('权限列表是数据', res)
        // 保存数据
        // 数组数据转成tree
        this.list = tranListToTreeData(res.data)
      } catch (err) {
        console.log('错误提示', err)
      }
    },
    // 根据roleId获取当前这个角色已经具备的权限
    async loadPermissionByRoleId() {
      try {
        const res = await getRoleDetail(this.roleId)
        console.log('获取当前角色的已有的权限点数据', res)
        // 设置当前选中的节点
        this.$refs.refTree.setCheckedKeys(res.data.permIds)
      } catch (err) {
        console.log('错误提示', err)
      }
    },
    // 取消按钮
    hCancel() {
    // 通过父组件去关闭弹层
      this.$emit('close')
    },
    // 确定按钮
    async hSubmit() {
      try {
        const permIds = this.$refs.refTree.getCheckedKeys()
        await assignPerm({ id: this.roleId, permIds })
        console.log(permIds)
        this.$message.success('操作角色权限成功') /
        // 关闭弹出层
        this.$emit('close')
      } catch (err) {
        console.log(err)
      }
    }
  }
}
</script>

<style>

</style>
